package com.xxxy.jsq.action.distrib;

import com.alibaba.fastjson2.JSONObject;
import com.xxxy.jsq.dao.DistribDao;
import com.xxxy.jsq.model.Distrib;
import com.xxxy.jsq.model.Page;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/getAllDistribsPageServlet")
public class GetAllDistribsPageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置请求和响应编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        // 创建模型对象和DAO对象
        Distrib model = new Distrib();
        DistribDao dao = new DistribDao();

        // 获取查询参数
        String distribFlag = request.getParameter("distrib_flag");
        String roleId = request.getParameter("role_id");
        String worksId = request.getParameter("works_id");

        // 设置查询条件
        if(distribFlag != null && !distribFlag.equals("")) {
            model.setDistribFlag(distribFlag);
        }
        if(roleId != null && !roleId.equals("")) {
            model.setRoleId(roleId);
        }
        if(worksId != null && !worksId.equals("")) {
            model.setWorksId(worksId);
        }

        // 处理分页参数
        String cpage = request.getParameter("page");
        String limit = request.getParameter("limit");
        Page page = new Page();

        if(cpage != null && !cpage.equals("")) {
            page.setCurrentPage(Integer.parseInt(cpage));
            page.setCount(Integer.parseInt(limit));
        }

        // 执行查询
        List<Distrib> list = dao.getAllDataByPage(model, page);
        int total = dao.getCount(model);

        // 构建JSON响应
        JSONObject jo = new JSONObject();
        jo.put("code", 0);
        jo.put("msg", "查询成功");
        jo.put("count", total);
        jo.put("data", list);

        // 输出响应
        PrintWriter out = response.getWriter();
        out.print(jo.toString());
        out.flush();
        out.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}